const unitArray = ["bytes", "KB", "MB", "GB", "TB"];

const StoreUtils = {
	getStore(name) {
		if (window.localStorage != null && window.localStorage.getItem(name)) {
			let data = window.localStorage.getItem(name);
			if (data !== undefined && typeof data === "string") {
				return JSON.parse(data);
			}
			return data;
		}
	},

	setStore(name, value) {
		window.localStorage.setItem(name, JSON.stringify(value));
	},

	getSessionStore(name) {
		if (window.sessionStorage != null && window.sessionStorage.getItem("vuex")) {
			let data = window.sessionStorage.getItem("vuex");
			if (data !== undefined && typeof data === "string") {
				return JSON.parse(data)[name];
			}
			return data[name];
		}
	},

	setVuexStore(state) {
		window.sessionStorage.setItem("vuex", JSON.stringify(state));
	},

	setSessionStore(name, value) {
		if (window.sessionStorage != null && window.sessionStorage.getItem("vuex")) {
			let data = window.sessionStorage.getItem("vuex");
			data[name] = value;
			window.sessionStorage.setItem("vuex", JSON.stringify(data));
		}
	},

	//文件限制大小为10KB
	overLimitSize(data) {
		let sizeArray = this.getCommitSize(data).split(" ");
		if (unitArray.indexOf(sizeArray[1]) > 1) {
			return true;
		}
		if (unitArray.indexOf(sizeArray[1]) === 1) {
			if (sizeArray[0] >= 10) {
				return true;
			}
		}
		return false;
	},

	getCommitSize(item) {
		let size = JSON.stringify(item).length * 2;
		let sizeUnit = 0;

		while (size > 1024) {
			size /= 1024;
			++sizeUnit;
		}
		return `${size.toFixed(2)} ${this.unitArray[sizeUnit]}`;
	}
};

export default StoreUtils;
